package me.zhengjie.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.dao.MaterialDao;
import me.zhengjie.juc.StoreLock;
import me.zhengjie.mapper.MaterialMapper;
import me.zhengjie.server.MaterialService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, MaterialDao> implements MaterialService {

    @Resource
    private MaterialMapper materialMapper;

    @Override
    public MaterialDao findDataOne(String itemBarCode) {
        LambdaUpdateWrapper<MaterialDao> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(MaterialDao::getItemBarCode, itemBarCode);
        return materialMapper.selectOne(wrapper);
    }

    @Override
    public List<MaterialDao> findDataList(List<String> itemBarCodeList) {
        return this.findDataList(itemBarCodeList, null);
    }

    @Override
    public List<MaterialDao> findDataDao(MaterialDao materialDao) {
        return this.findDataList(null, materialDao);
    }

    public List<MaterialDao> findDataList(List<String> itemBarCodeList, MaterialDao materialDao) {
        LambdaQueryWrapper<MaterialDao> wrapper = new LambdaQueryWrapper<>();
        if (itemBarCodeList != null && !itemBarCodeList.isEmpty()) {
            wrapper.in(MaterialDao::getItemBarCode, itemBarCodeList);
        }
        if (materialDao != null) {
            this.setQueryWrapper(wrapper, materialDao);
        }
        return this.list(wrapper);
    }

    public void setQueryWrapper(LambdaQueryWrapper<MaterialDao> wrapper, MaterialDao materialDao) {
        if (materialDao.getItemBarCode() != null) {
            wrapper.eq(MaterialDao::getItemBarCode, materialDao.getItemBarCode());
        }
        if (materialDao.getContainerCode() != null) {
            wrapper.eq(MaterialDao::getContainerCode, materialDao.getContainerCode());
        }
        if (materialDao.getWarehouse() != null) {
            wrapper.eq(MaterialDao::getWarehouse, materialDao.getWarehouse());
        }
        if (materialDao.getIssuePosition() != null) {
            wrapper.eq(MaterialDao::getIssuePosition, materialDao.getIssuePosition());
        }

        if (materialDao.getMaterialCode() != null) {
            wrapper.eq(MaterialDao::getMaterialCode, materialDao.getMaterialCode());
        }
        if (materialDao.getMaterialName() != null) {
            wrapper.eq(MaterialDao::getMaterialName, materialDao.getMaterialName());
        }
    }

    @Override
    public void updateDataByCode(MaterialDao materialDao) {
        LambdaUpdateWrapper<MaterialDao> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(MaterialDao::getItemBarCode, materialDao.getItemBarCode());
        this.update(materialDao, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDataByList(List<String> itemBarCodeList, MaterialDao materialDao) {
        LambdaUpdateWrapper<MaterialDao> wrapper = new LambdaUpdateWrapper<>();
        if (materialDao == null) {
            return false;
        }
        if (!itemBarCodeList.isEmpty()) {
            wrapper.in(MaterialDao::getItemBarCode, itemBarCodeList);
            if (materialDao.getContainerCode() != null) {
                wrapper.set(MaterialDao::getContainerCode, materialDao.getContainerCode());
            }
        } else if (materialDao.getContainerCode() != null) {
            wrapper.eq(MaterialDao::getContainerCode, materialDao.getContainerCode());
        }

        if (materialDao.getWarehouse() != null) {
            wrapper.set(MaterialDao::getWarehouse, materialDao.getWarehouse());
        }
        if (materialDao.getIssuePosition() != null) {
            wrapper.set(MaterialDao::getIssuePosition, materialDao.getIssuePosition());
        }
        if (materialDao.getDisable() != null) {
            wrapper.set(MaterialDao::getDisable, materialDao.getDisable());
        }
        if (materialDao.getDisableDes() != null) {
            wrapper.set(MaterialDao::getDisableDes, materialDao.getDisableDes());
        }
        if (materialDao.getDisableNotes() != null) {
            wrapper.set(MaterialDao::getDisableNotes, materialDao.getDisableNotes());
        }
        if (materialDao.getInventoryQuantity() != null) {
            wrapper.set(MaterialDao::getInventoryQuantity, materialDao.getInventoryQuantity());
        }
        return this.update(wrapper);
    }


    /**
     * 根据载具编码查询物料条码
     *
     * @param containerCode 载具编码
     * @return 物料条码
     */
    @Override
    public MaterialDao findItemBarCodeByContainerCode(String containerCode) {
        return materialMapper.findItemBarCodeByContainerCode(containerCode);
    }

    /**
     * 根据载具编码删除物料信息
     *
     * @param containerCode 载具编码
     */
    @Override
    public void deleteByContainerCode(String containerCode) {
        LambdaQueryWrapper<MaterialDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MaterialDao::getContainerCode, containerCode);
        this.remove(wrapper);
    }

    /**
     * 根据载具编码计算物料重量
     *
     * @param containerCode 载具编码
     * @return 物料重量
     */
    @Override
    public Double countTotalMaterialWeight(String containerCode) {
        return materialMapper.countTotalMaterialWeight(containerCode);
    }

//    @Override
//    public Page<ContainerExtractVo> findAvailableExtractData(InventoryExtractBaseVo baseVo) {
//        Page<ContainerExtractVo> page = new Page<>(baseVo.getPage(), baseVo.getSize());
//        try {
//
//            Page<ContainerExtractVo> availableData = materialMapper.findAvailableData(page, baseVo);
//            for (ContainerExtractVo record : availableData.getRecords()) {
//                String[] itemBarCodeList = record.getItemBarCodeList().split(",");
//                List<String> list = Arrays.asList(itemBarCodeList);
//                List<MaterialDao> barCodeList = this.findDataList(list);
//                record.setMaterialList(barCodeList);
//            }
//            return availableData;
//        }catch (Exception e){
//            page.setRecords(new ArrayList<>());
//            return page;
//        }
//    }
//
//    @Override
//    public Page<ContainerMoveVo> findAvailableMoveData(InventoryMoveBaseVo baseVo) {
//        Page<InventoryMoveBaseVo> page = new Page<>(baseVo.getPage(), baseVo.getSize());
//        return materialMapper.findAvailableMoveData(page, baseVo);
//    }


    @Override
    public void updateInventory(Double material, Double totalOutWeight) {
        // 加锁
        StoreLock.getReentrantInLock().lock();
        try {
            // 安全地更新库存（避免并发问题）
            if (material < totalOutWeight) {
                throw new RuntimeException("库存不足");
            }
        } finally {
            // 释放锁（必须在finally中，确保异常时也能释放）
            StoreLock.getReentrantInLock().unlock();
        }
    }

    @Override
    public String getMaterialCodeListStrByContainerCode(String containerCode) {

        // 根据载具编码查询物料信息
        List<MaterialDao> materialList = this.findDataDao(new MaterialDao().setContainerCode(containerCode));
        StringBuilder Str = new StringBuilder();
        for (MaterialDao materialDao : materialList) {
            Str.append(materialDao.getMaterialCode()).append(",");
        }
        return Str.substring(0, Str.length() - 1);
    }


//    @Override
//    public PageResult<MaterialDao> queryAll(MaterialDao criteria, Page<Object> page) {
//        return PageUtil.toPage(baseMapper.queryAll(criteria, page));
//    }
}
